package com.uzai.console.service.dy.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.doudian.open.api.buyin_doukePidCreate.BuyinDoukePidCreateRequest;
import com.doudian.open.api.buyin_doukePidCreate.BuyinDoukePidCreateResponse;
import com.doudian.open.api.buyin_doukePidCreate.param.BuyinDoukePidCreateParam;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.uzai.common.enums.SysMsgTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.CommonUtil;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.RandomUtil;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.entity.DyToken;
import com.uzai.console.entity.Merchant;
import com.uzai.console.mapper.DyTokenMapper;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.service.dy.DyTokenCallBackService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author liuqi
 * @date 2021年08月31日 20:10
 */
@Service
public class DyTokenCallBackServiceImpl implements DyTokenCallBackService {

    private Logger logger = LoggerFactory.getLogger(DyTokenCallBackServiceImpl.class);

    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private DyTokenMapper dyTokenMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

    @Transactional
    @Override
    public void add(DyToken dyToken) {
        Merchant merchant = merchantMapper.selectById(dyToken.getMerId());
        if (merchant==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "没有该运营商");
        }
        DyToken dyToken_old = dyTokenMapper.selectByAppdId(dyToken.getAppId());
        //该淘宝联盟账号不存在，则新增加
        if (dyToken_old == null){//新增
            dyToken.setId(IdWorker.getId());
            //pid
            String pid = null;
            BuyinDoukePidCreateRequest request = new BuyinDoukePidCreateRequest();
            BuyinDoukePidCreateParam param = request.getParam();
            param.setMediaType(1);
            param.setMediaName("uzai_3.0");
            //param.setMediaId(222L);
            param.setSiteName(RandomUtil.getSmsCode(6)); //随机6位字符
            AccessToken accessToken = AccessTokenBuilder.parse(dyToken.getAccessToken());

            logger.info("--获取抖音联盟token-- accessToken={}", accessToken.getAccessToken());

            BuyinDoukePidCreateResponse response = request.execute(accessToken);
            if(response != null && response.getData() != null){
                logger.info("--获取抖音联盟PID-- data={}", response.getData().toString());
                pid = response.getData().getPid();
            }
            if(StringUtils.isBlank(pid)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "抖客联盟创建PID失败");
            }
            dyToken.setPid(pid);
            dyTokenMapper.insertSelective(dyToken);

            //发送其他异常提醒
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(merchant.getId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OTHER_EXCEPTION.getValue()); //其他异常提醒
            //消息
            JSONObject ext = new JSONObject();
            StringBuilder content = new StringBuilder();
            content.append("抖音已增加联盟授权，账号").append(dyToken.getName());
            //当前操作员
            ext.put("content", content.toString());
            ext.put("phone", merchant.getMobile());
            ext.put("errorcode", content.toString());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---抖音添加联盟授权，发送其他异常消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);


        }else{ //修改

            logger.info(dyToken_old.getMerId() + "::" + dyToken.getMerId());
            if (dyToken_old.getMerId().longValue() != dyToken.getMerId().longValue()){
                Merchant merchant_old = merchantMapper.selectById(dyToken_old.getMerId());
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.ALIMM_ACCOUNT_EXIST, CommonUtil.mobileFormat(merchant_old.getMobile())));
            }

            dyToken_old.setAccessToken(dyToken.getAccessToken());
            dyToken_old.setRefreshToken(dyToken.getRefreshToken());
            dyToken_old.setExptime(dyToken.getExptime());
            dyToken_old.setUpdateTime(dyToken.getUpdateTime());
            int count = dyTokenMapper.updateByIdSelective(dyToken_old);
            if (count != 1){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.NET_ERROR);
            }
        }
    }

}
